<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\MallGoods;
use App\Model\MallGoodsSku;
use App\Model\MallShoplog;
use App\Model\MallUnionGoods;
use App\Model\OperationLogs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class GoodsController extends BaseController
{
    protected $model;
    public function __construct(Request $request, MallGoods $mallGoods)
    {
        parent::__construct($request);
        $this->model = $mallGoods;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $res = $this->model->getList($request);
        if ($res){
            $res = $res->toArray();
            $goods_list = (array)$res['data'];
            foreach ($goods_list as $key => $value) {
                if ($value['is_upgrade']==1){
                    $upgradeConfig = $this->model->getGupConfigList($value['goods_id']);
                    $res['data'][$key]['upgrade_config'] = (array) $upgradeConfig;
                }
            }
        }

        return $this->toJson(self::SUCCESS, $res);
    }

    public function show($type)
    {
        return $this->toJson(self::SUCCESS, $this->model->getGoodsByType($type));
    }

    public function unGiftByType($type){
        return $this->toJson(self::SUCCESS, $this->model->getUnGoodsByType($type));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'goods_name' => 'required|string|max:50',
//            'is_new' => 'required', Rule::in(0, 1),
            'is_show' => 'required', Rule::in(0, 1),
            'is_new_mount' => 'required', Rule::in(0, 1),
            'text_color' => 'required|string',
            //'sort' => 'required|integer',
            //'small_img' => 'required|string',
            'big_img' => 'required|string',
            'animate_resource' => 'required|string',
            //商品类型 0=其它 1=尊贵头像框 2=进场特效 3=气泡 4=名片 5=主页飘 6=尾灯 7=座驾 8=娱乐头像框 9=游戏皮肤 10=聊天背景 11=装饰背景卡
            'goods_type' => 'required', Rule::in(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
            'extra_type' => ['nullable', Rule::in(0,1)],

            //'level' => 'required|integer',
            //'renew_card_num' => 'required|integer',
            //'mall_goods_class' => 'required|integer',
            //'is_upgrade' => 'required|integer',
            //'cool_val' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = array_merge($request->all(), ['create_timestamp' => $_SERVER['REQUEST_TIME']]);

        $data['sort'] = isset($data['sort']) ? intval($data['sort']) : 0;
        $data['level'] = isset($data['level']) ? intval($data['level']) : 0;
        $data['renew_card_num'] = isset($data['renew_card_num']) ? intval($data['renew_card_num']) : 0;
        $data['mall_goods_class'] = isset($data['mall_goods_class']) ? intval($data['mall_goods_class']) : 0;
        $data['is_upgrade'] = isset($data['is_upgrade']) ? intval($data['is_upgrade']) : 0;
        $data['cool_val'] = isset($data['cool_val']) ? intval($data['cool_val']) : 0;
        $data['debris_num'] = isset($data['debris_num']) ? intval($data['debris_num']) : 0;

        if (isset($data['is_upgrade']) && $data['is_upgrade']==1){
            if (empty($data['upgrade_config'])){
                return $this->toJson(self::PARAM_ERROR, [], '可升级礼物upgrade_config必需');
            }
        }


        if (is_null($data['animate_resource_md5'])) {
            unset($data['animate_resource_md5']);
        }
        if (is_null($data['animate_resource_small'])) {
            unset($data['animate_resource_small']);
        }
        $data['small_img'] = $data['big_img'] ?: '';
        $data['vapc_json_url'] = isset($data['vapc_json_url']) ? (string) $data['vapc_json_url'] : '';
        $goods = $this->model->createGoods($data);
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR, $goods);
        }
        $data['goods_id'] = $goods['data']['goods_id'];

        OperationLogs::createData($request, OperationLogs::GOODS, '新增商品');
        return $this->toJson(self::SUCCESS, $data);
    }

    public function labelGet()
    {
        return $this->toJson(self::SUCCESS, $this->model->getLabel());
    }

    public function labelDel($id)
    {
        if (!$id) {
            return $this->toJson(self::PARAM_ERROR, [], 'id不能为空');
        }

        $res = $this->model->delLabel($id);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR);
        }

        return $this->toJson(self::SUCCESS);
    }

    public function labelCreate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'resource' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $goods = $this->model->labelCreate($request->all());
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR, $goods);
        }
        $data['label_id'] = $goods['data']['label_id'];

        OperationLogs::createData($request, OperationLogs::GOODS, '新增商品标签');
        return $this->toJson(self::SUCCESS, $data);
    }

    public function labelEdit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'name' => 'required',
            'resource' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $goods = $this->model->labelEdit($request->all());
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR);
        }
        return $this->toJson(self::SUCCESS);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'goods_name' => 'required|string|max:50',
//            'is_new' => 'required', Rule::in(0, 1),
            'is_show' => 'required', Rule::in(0, 1),
            'is_new_mount' => 'required', Rule::in(0, 1),
            'text_color' => 'required|string',
            //'sort' => 'required|integer',
//            'small_img' => 'required|string',
            'big_img' => 'required|string',
            'animate_resource' => 'required|string',
            //商品类型 0=其它 1=尊贵头像框 2=进场特效 3=气泡 4=名片 5=主页飘 6=尾灯 7=座驾 8=娱乐头像框 9=游戏皮肤 10=聊天背景 11=装饰背景卡
            'goods_type' => 'required', Rule::in(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
            'extra_type' => [ 'nullable', Rule::in(0,1)]
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = $request->except(['mall_goods_sku', '_url', 'token']);


        $data['sort'] = isset($data['sort']) ? intval($data['sort']) : 0;
        $data['level'] = isset($data['level']) ? intval($data['level']) : 0;
        $data['renew_card_num'] = isset($data['renew_card_num']) ? intval($data['renew_card_num']) : 0;
        $data['mall_goods_class'] = isset($data['mall_goods_class']) ? intval($data['mall_goods_class']) : 0;
        $data['is_upgrade'] = isset($data['is_upgrade']) ? intval($data['is_upgrade']) : 0;
        $data['cool_val'] = isset($data['cool_val']) ? intval($data['cool_val']) : 0;
        $data['debris_num'] = isset($data['debris_num']) ? intval($data['debris_num']) : 0;

        if (is_null($data['animate_resource_md5'])) {
            unset($data['animate_resource_md5']);
        }

        if (is_null($data['animate_resource_small'])) {
            unset($data['animate_resource_small']);
        }
        $data['small_img'] = $data['big_img'] ?: '';
        $data['vapc_json_url'] = isset($data['vapc_json_url']) ? (string) $data['vapc_json_url'] : '';

        $goods = $this->model->updateGoods($data);
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR, $goods);
        }
        OperationLogs::createData($request, OperationLogs::GOODS, '编辑商品',$id);
        return $this->toJson(self::SUCCESS);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $goods = $this->model->removeGoods(['goods_id' => $id]);
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR, $goods);
        }
//        $this->model->where(['goods_id' => $id])->delete();
//        MallGoodsSku::where(['goods_id' => $id])->delete();
        OperationLogs::createData($request, OperationLogs::GOODS, '删除商品',$id);
        return $this->toJson();
    }

    /**
     * 删除 sku
     * @param $sku_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroySku(Request $request, $sku_id)
    {
        return $this->toJson(self::ERROR_HAVE_NO_RIGHT, [], '不可在后台删除SKU');

        $mallGoodsSku = MallGoodsSku::find($sku_id);

        if (MallGoodsSku::where(['goods_id' => $mallGoodsSku->goods_id])->count() <= 1) {
            return $this->toJson(self::ERROR_HAVE_NO_RIGHT, [], '最后一条不允许删除');
        }
        $gift = $this->model->removeData(['sku_id' => $sku_id]);
        if ($gift['code'] !== 0) {
            return $this->toJson(self::ERROR, $gift);
        }
        OperationLogs::createData($request, OperationLogs::GOODS, '删除 SKU',$sku_id);
        return $this->toJson();
    }

    /**
     * 更新 sku
     * @param $sku_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDefaultSku(Request $request, $sku_id)
    {
        $mallGoodsSku = MallGoodsSku::find($sku_id);
        $gift = $this->model->updateData(['goods_id' => $mallGoodsSku['goods_id'], 'sku_id' => $sku_id, 'default' => 1]);
        if ($gift['code'] !== 0) {
            return $this->toJson(self::ERROR, $gift);
        }
//        MallGoodsSku::where(['goods_id' => $mallGoodsSku['goods_id']])->update(['default' => 0]);
//
//        $mallGoodsSku->default = 1;
//        $mallGoodsSku->save();
        OperationLogs::createData($request, OperationLogs::GOODS, '设置默认 SKU',$sku_id);
        return $this->toJson();
    }

    public function updateSku(Request $request, $sku_id)
    {
//        $mallGoodsSku = MallGoodsSku::find($sku_id);
//        $mallGoodsSku->time_limit = $request->input('time_limit');
//        $mallGoodsSku->price = $request->input('price');
//        $mallGoodsSku->save();
        $gift = $this->model->updateData($request->except('_url', 'token'));
        if ($gift['code'] !== 0) {
            return $this->toJson(self::ERROR, $gift);
        }
        OperationLogs::createData($request, OperationLogs::GOODS, '编辑 SKU',$sku_id);
        return $this->toJson();
    }

    /**
     * 新增价格
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function storeSku(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'time_limit' => 'required|integer',
            'price' => 'required|integer'
        ], [
            'time_limit.required' => '天数不可为空',
            'price.required' => '价格不可为空'
        ]);


        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = array_merge($request->except('token'), ['create_timestamp' => $_SERVER['REQUEST_TIME']]);
        $sku = $this->model->createData($data);
        if ($sku['code'] !== 0) {
            return $this->toJson(self::ERROR, $sku);
        }
        $data['goods_id'] = intval($data['goods_id']);
        $data['sku_id'] = intval($sku['data']['sku_id']);
        $data['default'] = 0;
        OperationLogs::createData($request, OperationLogs::GOODS, '新增价格');
        return $this->toJson(self::SUCCESS, $data);
    }

    /**
     * 商品统计
     * @param Request $request
     * @param MallShoplog $mallShoplog
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsGoods(Request $request, MallShoplog $mallShoplog)
    {
        $validator = Validator::make($request->all(), [
            'start_date' => 'nullable|date_format:Y-m-d',
            'end_date' => 'nullable|date_format:Y-m-d',
            'type' => 'required', Rule::in(0, 1, 2, 3)
        ]);

        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        return $this->toJson(self::SUCCESS, $mallShoplog->statisticsGoods($request->all()));
    }

    /**
     * 商品周期统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsGoodsCycle(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'goods_type' => 'required', Rule::in(0, 1, 2, 3)
        ]);

        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        return $this->toJson(self::SUCCESS, $this->model->statisticsGoodsCycle($request->all()));
    }

    /**
     * 获取商品的 sku
     * @param $goods_id
     * @param MallGoodsSku $mallGoodsSku
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSku($goods_id, MallGoodsSku $mallGoodsSku)
    {
        return $this->toJson(self::SUCCESS, $mallGoodsSku->getSkuByGoodsId($goods_id));
    }

    public function remoteSearchGoods(Request $request, MallGoods $mallGoods)
    {
        $name = $request->input('name');
        return $this->toJson(self::SUCCESS, $mallGoods->getGoodByGoodName($name));
    }

    public function remoteSearchByGoodsId($id, MallGoods $mallGoods)
    {
        return $this->toJson(self::SUCCESS, $mallGoods->getGoodByGoodId($id));
    }

    public function ungiftGet(Request $request,MallUnionGoods $mallUnionGoods){
        return $this->toJson(self::SUCCESS, $mallUnionGoods->getlist($request));
    }

    public function ungiftCreate(Request $request,MallUnionGoods $mallUnionGoods){
        return $this->toJson(self::SUCCESS, $mallUnionGoods->ungiftCreate($request));
    }

    public function ungiftUpdate(Request $request,MallUnionGoods $mallUnionGoods){
        return $this->toJson(self::SUCCESS, $mallUnionGoods->ungiftUpdate($request));
    }
    public function ungiftLog(Request $request,MallUnionGoods $mallUnionGoods){
        return $this->toJson(self::SUCCESS, $mallUnionGoods->ungiftBackLog($request));
    }


    // 商品等级
    public function getGoodsLevelList(Request $request, MallGoods $mallGoods)
    {
        $where = [];
        $res = $mallGoods -> getGoodsLevelList($where);
        if ($res && $res['code']==0){
            return $this->toJson(self::SUCCESS, $res['data']??[]);
        }

        return $this->toJson(self::ERROR, [],$res['msg']);
    }

}
